<template>
  <view class="uni-view-main">
    <view class="uni-voucher-user">
      {{ '欢迎您来领取商家优惠劵' }}
    </view>

    <view class="uni-voucher-pay" v-if="canIUse">
      <mkt v-if="cityCode"
           :cityCode="cityCode"
           :mode="'AUTOMATIC'"
           :boothCode="'MERCHANT_SELF_TINYAPP'"
           :title="title"
           :version="version"
           :showVoucherCount="true"
           onRender="onRender"
           onApplySuccess="onApplySuccess"
           onApplyFail="onApplyFail"
      >
      </mkt>
    </view>

    <view class="uni-voucher-tips">
      <view class="uni-voucher-tips-text">
        {{ '您也可以直接去付款' }}
      </view>
      <view class="uni-voucher-tips-button" @tap="navBackPay">
        {{ '我要付款' }}
      </view>
    </view>
  </view>
</template>

<script>
import { mapMutations } from 'vuex';

let _this;
export default {
  data() {
    return {
      shopId: null,
      shopInfo: null,
      authCode: null,
      authPlatform: null,
      canIUse: false,
      cityCode: '530100',
      title: null,
      version: '1'
    }
  },
  onLoad() {
    _this = this;
    _this.$scope.onRender = _this.onRender.bind(_this);
    _this.$scope.onApplySuccess = _this.onApplySuccess.bind(_this);
    _this.$scope.onApplyFail = _this.onApplyFail.bind(_this);
  },
  onShow() {
    _this.shopId = uni.getStorageSync("shopId");

    uni.showLoading({
      mask: true,
      title: '加载中'
    });

    let tokenExpired = uni.getStorageSync('uni_id_token_expired') ? uni.getStorageSync('uni_id_token_expired') : 0;
    if (!tokenExpired || tokenExpired < new Date().getTime()) {
      _this.getAuthCode();
    }else{
      _this.loadShopInfo();
    }
  },
  methods: {
    ...mapMutations(['login']),

    onRender(e){
      console.log('onRender: ', e);
    },
    onApplySuccess(e){
      console.log('onApplySuccess: ', e);

      uni.showToast({
        title: '领取优惠劵成功',
        icon: 'none'
      });

      let timer = setTimeout(function(){
        uni.navigateTo({
          url: '/pages/gathering/pay/pay'
        });
        clearTimeout(timer);
      }, 1000);
    },
    onApplyFail(e){
      console.log('onApplyFail: ', e);

      uni.showToast({
        title: '领取优惠劵失败',
        icon: 'none'
      });
    },
    judgeUse(){
      // #ifdef MP-ALIPAY
      _this.canIUse = Boolean(my.canIUse('mkt'));
      // #endif
    },
    valueCityCode(){
      if(_this.shopInfo && _this.shopInfo.enterprise_city){
        _this.cityCode = _this.shopInfo.enterprise_city;
      }
    },
    getAuthCode(){
      // #ifdef MP-ALIPAY
      _this.authPlatform = 'alipay';

      uni.login({
        scopes: ['auth_base'],
        success(res){
          if(res && res.code){
            _this.authCode = res.code;
            _this.cloudLogin();
          }else{
            uni.hideLoading();
            _this.$api.msg('获取支付宝授权码失败');
          }
        }
      });
      // #endif

      // #ifdef MP-WEIXIN
      _this.authPlatform = 'wechat';

      uni.login({
        provider: 'weixin',
        onlyAuthorize: true,
        success(res){
          if(res && res.code){
            _this.authCode = res.code;
            _this.cloudLogin();
          }else{
            uni.hideLoading();
            _this.$api.msg('获取微信授权码失败');
          }
        }
      });
      // #endif
    },
    cloudLogin(){
      if(!_this.authCode){
        uni.hideLoading();
        _this.$api.msg('用户授权码参数丢失');
        return;
      }
      if(!_this.authPlatform){
        uni.hideLoading();
        _this.$api.msg('用户授权平台参数丢失');
        return;
      }

      let methodName;
      if('alipay' === _this.authPlatform){
        methodName = 'member/loginByAlipay';
      }else if('wechat' === _this.authPlatform){
        methodName = 'member/loginByWeixin';
      }else{
        _this.$api.msg('用户授权平台参数不正确');
        return;
      }

      let params = {
        app_id: _this.appId,
        code: _this.authCode
      };

      _this.$func.wmzmall.call(methodName, params).then(res => {
        if(res && res.code && 200 === res.code && res.datas){
          _this.login(res.datas);
          _this.loadShopInfo();
        }else if(res.msg){
          uni.hideLoading();
          _this.$api.msg(res.msg);
        }else{
          uni.hideLoading();
          _this.$api.msg('用户授权登录失败');
        }
      }).catch(err => {
        uni.hideLoading();
        console.log(err);
      });
    },
    loadShopInfo(){
      _this.$func.wmzmall.call('shop/getShopInfoById', { shop_id: _this.shopId }).then(res => {
        if(res && res.code && 200 === res.code && res.datas && res.datas.data){
          _this.shopInfo = res.datas.data;
          _this.judgeUse();
          _this.valueCityCode();
        }else if(res.msg){
          _this.$api.msg(res.msg);
        }else{
          _this.$api.msg('获取门店信息数据失败');
        }
      }).catch(err => {
        console.log(err);
      }).finally(() => {
        uni.hideLoading();
      });
    },
    navBackPay(){
      uni.navigateTo({
        url: '/pages/gathering/pay/pay'
      });
    }
  }
}
</script>

<style lang="scss">
@import '~@/pages/voucher/voucher.scss';
</style>
